package com.carrental.rental.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.carrental.common.api.PageResult;
import com.carrental.common.exception.BusinessException;

import com.carrental.rental.dto.OverdueFeeNoticeDTO;
import com.carrental.rental.dto.RentalRenewDTO;
import com.carrental.rental.dto.RentalStatusQueryDTO;
import com.carrental.rental.dto.RentalStatusReminderDTO;
import com.carrental.rental.entity.RentalRecord;
import com.carrental.rental.mapper.RentalRecordMapper;
import com.carrental.rental.service.RentalStatusService;
import com.carrental.rental.vo.RentalStatusVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 租赁状态服务实现类
 */
@Slf4j
@Service
public class RentalStatusServiceImpl implements RentalStatusService {

    @Autowired
    private RentalRecordMapper rentalRecordMapper;

    @Override
    public PageResult<RentalStatusVO> getRentalStatusPage(RentalStatusQueryDTO queryDTO) {
        Page<RentalStatusVO> page = new Page<>(queryDTO.getCurrent(), queryDTO.getSize());
        page = (Page<RentalStatusVO>) rentalRecordMapper.selectRentalStatusPage(
                page, 
                queryDTO.getLicensePlate(), 
                queryDTO.getRentalStatus(), 
                queryDTO.getExpiryWarning());
        
        PageResult<RentalStatusVO> pageResult = new PageResult<>();
        pageResult.setRecords(page.getRecords());
        pageResult.setTotal((int)page.getTotal());
        pageResult.setCurrent((int)page.getCurrent());
        pageResult.setSize((int)page.getSize());
        pageResult.setPages((int)page.getPages());
        
        return pageResult;
    }

    @Override
    public Map<String, Object> getRentalStats() {
        Map<String, Object> stats = new HashMap<>();
        stats.put("totalVehicles", rentalRecordMapper.countTotalVehicles());
        stats.put("rentedVehicles", rentalRecordMapper.countRentedVehicles());
        stats.put("expiringVehicles", rentalRecordMapper.countExpiringVehicles());
        stats.put("overdueVehicles", rentalRecordMapper.countOverdueVehicles());
        return stats;
    }

    @Override
    public void sendReminder(RentalStatusReminderDTO reminderDTO) {
        // 这里实现发送提醒的逻辑
        // 实际项目中可能需要调用短信或电话服务
        
        log.info("发送租赁提醒，租赁记录ID: {}, 提醒类型: {}, 提醒内容: {}", 
                reminderDTO.getIds(), reminderDTO.getRemindType(), reminderDTO.getContent());
        
        // 模拟发送提醒
        if (reminderDTO.getRemindType() == 1) {
            log.info("发送短信提醒成功");
        } else if (reminderDTO.getRemindType() == 2) {
            log.info("发送电话提醒成功");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void renewRental(RentalRenewDTO renewDTO) {
        // 查询租赁记录
        RentalRecord record = rentalRecordMapper.selectById(renewDTO.getId());
        if (record == null) {
            throw new BusinessException("租赁记录不存在");
        }
        
        // 计算新的结束时间
        LocalDateTime newEndTime = record.getEndTime().plusDays(renewDTO.getDays());
        
        // 更新租赁记录
        record.setEndTime(newEndTime);
        record.setUpdateTime(LocalDateTime.now());
        
        // 如果是已超期状态，则更新为租赁中
        if (record.getStatus() == 2) {
            record.setStatus(1);
        }
        
        rentalRecordMapper.updateById(record);
        
        log.info("续租成功，租赁记录ID: {}, 续租天数: {}, 新到期时间: {}", 
                renewDTO.getId(), renewDTO.getDays(), 
                newEndTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
    }

    @Override
    public void sendOverdueFeeNotice(OverdueFeeNoticeDTO noticeDTO) {
        // 这里实现发送超期费用通知的逻辑
        // 实际项目中可能需要调用短信或邮件服务
        
        log.info("发送超期费用通知，租赁记录ID: {}, 超期费用: {}", 
                noticeDTO.getId(), noticeDTO.getOverdueFee());
        
        // 模拟发送通知
        log.info("发送超期费用通知成功");
    }

    @Override
    public void exportRentalStatus(RentalStatusQueryDTO queryDTO, HttpServletResponse response) {
        try {
            // 设置响应头
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String fileName = new String("车辆租赁状态数据.xlsx".getBytes("utf-8"), "ISO-8859-1");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName);
            
            // 查询数据
            queryDTO.setCurrent(1);
            queryDTO.setSize(Integer.MAX_VALUE); // 导出所有数据
            PageResult<RentalStatusVO> pageResult = getRentalStatusPage(queryDTO);
            List<RentalStatusVO> list = pageResult.getRecords();
            
            // 这里实现将数据写入Excel的逻辑
            // 实际项目中可能使用POI或EasyExcel等库
            
            // 模拟导出
            response.getWriter().write("导出成功，共" + list.size() + "条数据");
            
            log.info("导出租赁状态数据成功，共{}条数据", list.size());
        } catch (IOException e) {
            log.error("导出租赁状态数据失败", e);
        }
    }

    @Override
    public void generateRentalStatusReport(HttpServletResponse response) {
        try {
            // 设置响应头
            response.setContentType("application/pdf");
            response.setCharacterEncoding("utf-8");
            String fileName = new String("车辆租赁状态报表.pdf".getBytes("utf-8"), "ISO-8859-1");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName);
            
            // 这里实现生成PDF报表的逻辑
            // 实际项目中可能使用iText或JasperReports等库
            
            // 模拟生成报表
            response.getWriter().write("生成报表成功");
            
            log.info("生成租赁状态报表成功");
        } catch (IOException e) {
            log.error("生成租赁状态报表失败", e);
        }
    }
} 